    //
//  StockGrapth.m
//  iStock Global
//
//  Created by Andy on 2010/10/5.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import "StockTableQuote.h"
#import "StockGrapth.h"
#import "GraphSetup.h"
#import "CPTPlotRange.h"
#import "AppDelegate.h" 


CGFloat distanceBetweenTwoPoints(CGPoint firstPoint,CGPoint secondPoint){
	CGFloat deltax=secondPoint.x-firstPoint.x;
    CGFloat deltay=secondPoint.y-firstPoint.y;
	return sqrt(deltax*deltax+deltay*deltay);
}

@implementation StockGrapth

@synthesize graph ;
@synthesize layerHost;
@synthesize delgete;
@synthesize graph_dwm;
@synthesize AppleDeglate;


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
     
    
    return YES;
}
#pragma mark -
#pragma mark  segmentChanged_Delgete

-(void)segmentChanged_Day{
    NSLog(@"DDay");
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        // 
        if (ActivityIndicator==nil ) {
            ActivityIndicator=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(130,210, 60, 60)];	
            ActivityIndicator.activityIndicatorViewStyle=UIActivityIndicatorViewStyleWhiteLarge;
            [self.view addSubview:ActivityIndicator];            
            
        }
        
        [ActivityIndicator  startAnimating];         
    }

    
    
    
    graph_dwm=@"d";
       
    
    [segmetnctl setUserInteractionEnabled:NO];		
    
    
    [self.delgete SegmetnctlChange:graph_dwm indexr:0];    
    
} 
-(void)segmentChanged_Month{
    NSLog(@"MMonth");
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        // 
        if (ActivityIndicator==nil ) {
            ActivityIndicator=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(320,450, 60, 60)];	
            ActivityIndicator.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
            [self.view addSubview:ActivityIndicator];            
            
        }
        
        [ActivityIndicator  startAnimating];         
    }
    
    
    
    graph_dwm=@"m";
    
    [segmetnctl setUserInteractionEnabled:NO];		
    
    
    [self.delgete SegmetnctlChange:graph_dwm indexr:0];    
    
}
-(void)segmentChanged_Week{
   NSLog(@"WWeek");  
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        // 
        if (ActivityIndicator==nil ) {
            ActivityIndicator=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(320,450, 60, 60)];	
            ActivityIndicator.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
            [self.view addSubview:ActivityIndicator];            
            
        }
        
        [ActivityIndicator  startAnimating];         
    }
    
    
    graph_dwm=@"w";
    
    [segmetnctl setUserInteractionEnabled:NO];		
    
    
    [self.delgete SegmetnctlChange:graph_dwm indexr:0];    
    
    
}
-(void)SplitViewDelegate_Delgete_showInfo:(UIBarButtonItem *) barbuttonitem{
    NSLog(@"SplitViewDelegate_Delgete_showInfo");
     
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ) {
            //垂直
            NSLog(@"垂直");
            if ( [[(AppDelegate * )AppleDeglate can_use_graph_setup ] isEqualToString: @"YES"] ) {
                if ([popController isPopoverVisible]==NO   ) {
                    //主圖消失  
                    NSLog(@"主圖消失");
                    [[(AppDelegate * )AppleDeglate Master_popController]  dismissPopoverAnimated:YES]; 
                    
                    GraphSetup *controller = [[GraphSetup alloc] initWithTargetSymbol:stockdata];
                    controller.AppleDeglate=AppleDeglate;
                    controller.delegate = self;
                    controller.barbuttonitem=barbuttonitem;
                    popController = [[UIPopoverController alloc] initWithContentViewController:controller];
                    
                    controller.delegate_UIPopoverController=popController;
                    [controller release];
                    
                    
                    popController.popoverContentSize = CGSizeMake(320,460);
                    
                    [popController presentPopoverFromBarButtonItem:barbuttonitem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];                  
                    
                    ////如果點選次圖 則將垂直顯示的走勢圖設定的浮動圖銷失           
                    [(AppDelegate * )AppleDeglate  Get_popController_info: popController]; 
                    
                }                          
            }
                 
                    
                    
        }
        else{
            //水平
            //標記:app 審核ＩＰＡＤ畫面重疊錯誤的地方
            //popController 點選多次後就會重疊
            
            if ([popController isPopoverVisible]==NO) {
                GraphSetup *controller = [[GraphSetup alloc] initWithTargetSymbol:stockdata];
                controller.delegate = self;
                  controller.AppleDeglate=AppleDeglate;                
                controller.barbuttonitem=barbuttonitem;
                popController = [[UIPopoverController alloc] initWithContentViewController:controller];
                
                controller.delegate_UIPopoverController=popController;
                [controller release];
                popController.popoverContentSize = CGSizeMake(320,460);
                
                [popController presentPopoverFromBarButtonItem:barbuttonitem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
                
                  [(AppDelegate * )AppleDeglate  Get_popController_info: popController]; 
            }            
            
                               
            
            
        }
        
        
    }    
              
           
    
        
    
}

#pragma mark -
#pragma mark  啓動方法
//重新繪圖時 執行明令
-(void)resetLocationData{
	//因為切換日週月的關係 所以必須將位置資訊重新設定
	 
        NSLog(@"resetLocationData_START");
        NSLog(@"finance account=%i ", [stockdata.financialData count] );    
        
        if ([stockdata.financialData count] <=  graph_show_length) {
            
            KBarSartLocation_move=1;
            KBarLength=[stockdata.financialData count];	
            KBarSartLocation=[stockdata.financialData count] -KBarLength;	
            KBarSartLocation_limitLeft=stockdata.financialData.count -KBarLength;
            
        }
        else {
            
            KBarSartLocation_move=5;
            KBarLength= graph_show_length;	
            KBarSartLocation=[stockdata.financialData count] -KBarLength;	
            KBarSartLocation_limitLeft=stockdata.financialData.count -KBarLength;
            
        }
        
        NSLog(@"start KBarSartLocation =%i KBarLength=%i finance account=%i  KBarSartLocation_limitLeft=%i ",KBarSartLocation,KBarLength , [stockdata.financialData count],KBarSartLocation_limitLeft);    
        
        
        
        NSLog(@"resetLocationData_END");
       
}



-(id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
	self= [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self ) {
		//self.title=@"ff";
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
            
            graph_show_length=120;
            
        }         
        else{
            
            graph_show_length=60;
            
        }            
        
        
        
	}
	return self;  
}
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
 
    
    [self resetLocationData];
	    
	//設定底層畫布 第ㄧ次建置時
    
    
	CPTGraphHostingView * newView = [[CPTGraphHostingView alloc]initWithFrame:[[UIScreen mainScreen] applicationFrame]];
    
    
	newView.delegete=self;
	self.view = newView;
  
    
    
	//newView.multipleTouchEnabled=YES;
	//newView.userInteractionEnabled=YES;
	
	[newView release];
	
	// NSLog(stockdata.symbol);    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        
        
        
    }         
    else{
        NSArray *textoptionarray;
              
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];                
        //標記:Yahoo與Google 資料選擇修改位置 日 周 月 線產生        
        if ([[prefs objectForKey:@"isYahoo"] boolValue]==YES)  {                 
            textoptionarray=[NSArray arrayWithObjects:@"D",@"W",@"M",nil]; 
        }  	                    
        else{
            textoptionarray=[NSArray arrayWithObjects:@"D",@"W",nil]; 
        }
        
        
       
        
        segmetnctl=[[UISegmentedControl alloc] initWithItems:textoptionarray];
        
        
        if ([graph_dwm isEqualToString:@"d"]) {
            segmetnctl.selectedSegmentIndex=0;
        }
        else if([graph_dwm isEqualToString:@"w"]){
            segmetnctl.selectedSegmentIndex=1;
            
        }
        else if([graph_dwm isEqualToString:@"m"]){
            segmetnctl.selectedSegmentIndex=2;
            
        }	
        
        
        [segmetnctl addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
        
        segmetnctl.frame=CGRectMake(0, 0, 320, 30);
        
        
        
        
                
        self.navigationItem.titleView=segmetnctl;
        [segmetnctl autorelease];	
        
        
        //*  圖形設定扭 因為要上ＡＰＰＳＴＯＲＥ暫時關閉
        UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
        [infoButton addTarget:self action:@selector(showInfo) forControlEvents:UIControlEventTouchUpInside];
       
        UIBarButtonItem *temb= [[UIBarButtonItem alloc] initWithCustomView:infoButton] ;
        self.navigationItem.rightBarButtonItem =temb    ;
        [temb release];
        
       
    }    
     /*  
    if ([graph retainCount]>0) {
        int graph_retaincount;
        graph_retaincount=[graph retainCount];
        for (int i=0; i <graph_retaincount; i++) {
            NSLog(@"a******graph retainCount=%i",[graph retainCount]);    
            [graph release];
            NSLog(@"b******graph retainCount=%i",[graph retainCount]);    
        }
        
        
    }
   */
    
    if (graph) {
         
        
    }   
    else{
        
     
               
       graph = [[CPTXYGraph alloc] initWithFrame: self.view.bounds] ; 
        
    }     
       
   // graph = [[CPXYGraph alloc] initWithFrame: self.view.bounds];    
   
    
	//CPLayerHostingView *hostingView = (CPLayerHostingView *)self.view;
	//hostingView.hostedLayer = graph;
	self.layerHost=  (CPTGraphHostingView *)self.view;
	self.layerHost.hostedGraph=graph ;
	[graph release];
    
	//self.layerHost.multipleTouchEnabled=YES;
	//self.layerHost.userInteractionEnabled=YES;
	
	CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
    [graph applyTheme:theme];
	
    
    
	graph.paddingTop = 1.0;
	graph.paddingBottom = 1.0;
	graph.paddingLeft = 1.0;
	graph.paddingRight =1.0;
	
	
	//四角圓弧度 越大值表示月圓
	graph.plotAreaFrame.cornerRadius = 0.0f;
	
	CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
	//邊線顏色
	borderLineStyle.lineColor = [CPTColor yellowColor];
	//邊線的細粗程度
	borderLineStyle.lineWidth = 0.0f;
	//設定邊線款式
	graph.plotAreaFrame.borderLineStyle = borderLineStyle;		
	
}
#pragma mark -
#pragma mark  走勢圖設定
-(void)showInfo{
	 
	GraphSetup *controller = [[GraphSetup alloc] initWithTargetSymbol:stockdata];
	controller.delegate = self;
	
	controller.modalTransitionStyle =UIModalTransitionStyleFlipHorizontal; //UIModalTransitionStyleFlipHorizontal;
	[self presentModalViewController:controller animated:YES];
	
	[controller release];	
}
- (void)flipsideViewControllerDidFinish:(GraphSetup *)controller {
    //走勢圖設定結束
	NSLog(@"走勢圖設定結束");
	[self.delgete SegmetnctlChange:graph_dwm indexr:0];	
	
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        // 
        if (ActivityIndicator==nil ) {
            ActivityIndicator=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(320,450, 60, 60)];	
            ActivityIndicator.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
            [self.view addSubview:ActivityIndicator];            
            
        }
      	        
        [ActivityIndicator  startAnimating];         
    }
    else{
       //將 ModalViewControlle 消失
        [self dismissModalViewControllerAnimated:YES];   
    }
    
    
    
    
	 
}
-(void)stopActivityIndicator{
    NSLog(@"stopActivityIndicator");
   [ActivityIndicator stopAnimating];

}


#pragma mark -
#pragma mark  繪圖左邊註解
-(void)showLeft_layer:(NSMutableDictionary *)aparaobject fdata:(NSMutableDictionary *)lastfdata graph_line:(CPTTextLayer *)cptextline{	
	 NSLog(@"Line idendfiler=%@", [aparaobject valueForKey:@"idendfiler"]);
	
    if ([[aparaobject valueForKey:@"idendfiler"] hasPrefix:@"LF"]) {
		NSRange range={2,1};
		NSString *index;
		index= [(NSString *)[aparaobject valueForKey:@"idendfiler"] substringWithRange:range ];
	    NSLog(@"%@",index);
		
		
		float LF_bout,LF_sout;
		int LF_b,LF_s;
		
		LF_b=[[lastfdata objectForKey:[[aparaobject valueForKey:@"idendfiler"] stringByAppendingString:@"_b"]] intValue];
		LF_s=[[lastfdata objectForKey:[[aparaobject valueForKey:@"idendfiler"] stringByAppendingString:@"_s"]] intValue];
		LF_bout=[[lastfdata objectForKey:[[aparaobject valueForKey:@"idendfiler"] stringByAppendingString:@"_bout"]] floatValue];
		LF_sout=[[lastfdata objectForKey:[[aparaobject valueForKey:@"idendfiler"] stringByAppendingString:@"_sout"]] floatValue];
		//作多
		if (LF_b==1) {
			cptextline.text=[[NSLocalizedString(@"Short If Close Under", @"Short If Close Under") stringByAppendingFormat:@"%@:",index ]stringByAppendingString:[NSString stringWithFormat:@"%0.03f",LF_bout]];
			CPTMutableTextStyle *textStyle =  [CPTMutableTextStyle textStyle] ;
			textStyle.color    =  [aparaobject valueForKey:@"Blinecolor"];
			textStyle.fontSize  = 13;	
			cptextline.textStyle=textStyle;	
		}
		//作空
		else if(LF_s==1) {
			cptextline.text=[[NSLocalizedString(@"Long If Close Over", @"Long If Close Over") stringByAppendingFormat:@"%@:",index ]stringByAppendingString:[NSString stringWithFormat:@"%0.03f",LF_sout]];
			CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
			textStyle.color    =  [aparaobject valueForKey:@"Slinecolor"];
			textStyle.fontSize  = 13;	
			cptextline.textStyle=textStyle;					
			
		}
		
			
		
		
	}
	
	else if([[aparaobject valueForKey:@"idendfiler"] hasPrefix:@"Cmesa"]) {
		//NSLog(@"MESA");
		NSRange range={5,1};
		NSString *index;
		index= [(NSString *)[aparaobject valueForKey:@"idendfiler"] substringWithRange:range ];
	    NSLog(@"%@",index);		
		
		
		float FAMA,MAMA;
	 
	    FAMA=[[lastfdata objectForKey:[[aparaobject valueForKey:@"idendfiler"] stringByAppendingString:@"FAMA"]] floatValue];
		MAMA=[[lastfdata objectForKey:[[aparaobject valueForKey:@"idendfiler"] stringByAppendingString:@"MAMA"]] floatValue];
		
		
		CPTTextLayer *Acptx;
		
		Acptx=[array_layer_lin objectAtIndex:index_array_layer_lin];
		Acptx.text=[NSString stringWithFormat:@"%@(%@):%0.03f",NSLocalizedString(@"MAMA", "Fast Trend"),index,MAMA];
		CPTMutableTextStyle   *textStyle = [CPTMutableTextStyle textStyle];
		textStyle.color    = [aparaobject valueForKey:@"MAMAlinecolor"];
		textStyle.fontSize  = 13;	
		Acptx.textStyle=textStyle;			
		
		if (index_array_layer_lin+1<[array_layer_lin count]) {
			index_array_layer_lin=index_array_layer_lin+1;			
		}
		
        Acptx=[array_layer_lin objectAtIndex:index_array_layer_lin];
		Acptx.text=[NSString stringWithFormat:@"%@(%@):%0.03f",NSLocalizedString(@"FAMA",  "Slow Trend"),index,FAMA];
		CPTMutableTextStyle *textStylea = [CPTMutableTextStyle textStyle];
		textStylea.color    =  [aparaobject valueForKey:@"FAMAlinecolor"];
		textStylea.fontSize  = 13;	
		Acptx.textStyle=textStylea;			
		if (index_array_layer_lin+1<[array_layer_lin count]) {
			index_array_layer_lin=index_array_layer_lin+1;			
		}
		
		
	}
    
	else if([[aparaobject valueForKey:@"idendfiler"] hasPrefix:@"Caverage"]) {	
		NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];		
		NSRange range={8,1};
		NSString *index;
		index=[@"number_MVindicator" stringByAppendingString: [[aparaobject valueForKey:@"idendfiler"] substringWithRange:range]];
		NSString *ma_para;
		ma_para=[prefs objectForKey:index];
		 
 
		
		float mva;
	    mva=[[lastfdata objectForKey: [aparaobject valueForKey:@"idendfiler"]   ] floatValue];		
		
		CPTTextLayer *Acptx;		
		Acptx=[array_layer_lin objectAtIndex:index_array_layer_lin];
		Acptx.text=[NSString stringWithFormat:@"%@(%@):%0.02f",NSLocalizedString([aparaobject valueForKey:@"idendfiler"],"移動均線"),ma_para,mva];
		CPTMutableTextStyle *textStylea = [CPTMutableTextStyle textStyle];
		textStylea.color    =  [aparaobject valueForKey:@"linecolor"];
		textStylea.fontSize  = 13;	
		Acptx.textStyle=textStylea;			
		if (index_array_layer_lin+1<[array_layer_lin count]) {
			index_array_layer_lin=index_array_layer_lin+1;			
		}
		
		
		
	}
	
	else if([[aparaobject valueForKey:@"idendfiler"] hasPrefix:@"KD"]) {
		//NSLog(@"MESA");
		float K,D;
		
	    K=[[lastfdata objectForKey: @"CKD_K"]  floatValue];
		D=[[lastfdata objectForKey: @"CKD_D"]  floatValue];
		
		
		CPTTextLayer *Acptx;
		
		Acptx=[array_layer_lin objectAtIndex:index_array_layer_lin];
		Acptx.text=[NSString stringWithFormat:@"K:%0.03f",K];
		CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
		textStyle.color    = [aparaobject valueForKey:@"Klinecolor"];
		textStyle.fontSize  = 13;	
		Acptx.textStyle=textStyle;			
		
		if (index_array_layer_lin+1<[array_layer_lin count]) {
			index_array_layer_lin=index_array_layer_lin+1;			
		}
		
        Acptx=[array_layer_lin objectAtIndex:index_array_layer_lin];
		Acptx.text=[NSString stringWithFormat:@"D:%0.03f",D];
		CPTMutableTextStyle *textStylea = [CPTMutableTextStyle textStyle];
		textStylea.color    =  [aparaobject valueForKey:@"Dlinecolor"];
		textStylea.fontSize  = 13;	
		Acptx.textStyle=textStylea;			
		if (index_array_layer_lin+1<[array_layer_lin count]) {
			index_array_layer_lin=index_array_layer_lin+1;			
		}
		
		
	}	
	
	else if([[aparaobject valueForKey:@"idendfiler"] hasPrefix:@"Volume"]) {	
		 	
		 NSLog(@"Volume");
		int  volume;
		
	    volume=[[lastfdata objectForKey: @"Volume"]  intValue];
	 
		
		
		CPTTextLayer *Acptx;
		
		Acptx=[array_layer_lin objectAtIndex:index_array_layer_lin];
		Acptx.text=[NSString stringWithFormat:@"Volume:%i",volume];
		CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
		textStyle.color   = [aparaobject valueForKey:@"lineColor"];
		textStyle.fontSize  = 13;	
		Acptx.textStyle=textStyle;			
		
		if (index_array_layer_lin+1<[array_layer_lin count]) {
			index_array_layer_lin=index_array_layer_lin+1;			
		}
		
         		 
	}
	
	//[lastfdata release];	
}

-(void)resize_graph_frame{
    NSLog(@"resize_graph_frame");
    CGRect f ;
    
    //1024 *768 44
    if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ){
        
        //垂直 尚未解決
        f.size.width = [[[(AppDelegate * )AppleDeglate dv] view] bounds].size.width;//704
        f.size.height = [[[(AppDelegate * )AppleDeglate dv] view] bounds].size.height-44;//724
        f.origin.x = 0;//
        f.origin.y = 44;//44
    }
    else{
        
        
        //水平
        f.size.width  = [[[(AppDelegate * )AppleDeglate dv] view] bounds].size.width;//704
        f.size.height = [[[(AppDelegate * )AppleDeglate dv] view] bounds].size.height-44;//724
        f.origin.x = 0;//
        f.origin.y = 44;//44
    }
    
    
    self.view.frame=f;
    
    
}

#pragma mark -
#pragma mark  繪圖起點

-(void)redrawChart:(BOOL)isreset{
    if (self.delgete!=nil)  {
        
        
        
        
            //如果是iPad 需要進行下面動作
            if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
                
                
                [(AppDelegate * )AppleDeglate  splitViewDelegate ].delgete=self;            
                
                [self resize_graph_frame]; 
                
                [[(AppDelegate * )AppleDeglate dv ].view addSubview:self.view];                        
                
                if([(AppDelegate * )AppleDeglate splitViewDelegate].toolBar != nil) {
                    
                    [[(AppDelegate * )AppleDeglate splitViewDelegate] add_toolbar_item];
                    
                }
                [(AppDelegate * )AppleDeglate Get_agraph:self];            
                
                
                
                
            }
            
            
            NSLog(@"redrawchart_start" );
            
            //NSLog(@"start KBarSartLocation =%i KBarLength=%i finance account=%i",KBarSartLocation,KBarLength , [stockdata.financialData count]);
            NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];		
            
            if (isreset==YES) {
                //NSLog(@"*****isreset=YES******");
                if ([stockdata.financialData count] <=  graph_show_length) {
                    //NSLog(@"resetLocationData_YES fc <60 financialData count=%i",[stockdata.financialData count]);
                    KBarSartLocation_move=1;
                    KBarLength=[stockdata.financialData count];	
                    KBarSartLocation=[stockdata.financialData count] -KBarLength;	
                    KBarSartLocation_limitLeft=[stockdata.financialData count] -KBarLength;
                    //NSLog(@"start KBarSartLocation =%i KBarLength=%i finance account=%i",KBarSartLocation,KBarLength , [stockdata.financialData count]);
                    
                }
                else {
                    //NSLog(@"resetLocationData_NO fc>60");		
                    //NSLog(@"start KBarSartLocation =%i KBarLength=%i finance account=%i",KBarSartLocation,KBarLength , [stockdata.financialData count]);
                    
                    KBarSartLocation_move=5;
                    KBarLength= graph_show_length;	
                    KBarSartLocation=[stockdata.financialData count] -KBarLength;	
                    KBarSartLocation_limitLeft=[stockdata.financialData count] -KBarLength;
                    //NSLog(@"start KBarSartLocation =%i KBarLength=%i finance account=%i",KBarSartLocation,KBarLength , [stockdata.financialData count]);
                    
                }		
            }
            
            //預防陣列超過
            if (KBarLength+KBarSartLocation>[stockdata.financialData count]) {
                //NSLog(@"陣列超過");
                
                if ([stockdata.financialData count]>= graph_show_length) {
                    KBarLength= graph_show_length;
                    KBarSartLocation=[stockdata.financialData count]-KBarLength;
                    
                    KBarSartLocation_limitLeft=[stockdata.financialData count] -KBarLength;			
                }
                else {
                    KBarLength=[stockdata.financialData count];
                    KBarSartLocation=0;
                    
                    KBarSartLocation_limitLeft=[stockdata.financialData count] -KBarLength;				
                }
                
                //NSLog(@"fix KBarSartLocation =%i KBarLength=%i finance account=%i",KBarSartLocation,KBarLength , [stockdata.financialData count]);
            }
            
            
            
        
            //重要錯誤 如果在ipad上顯示標籤就容易當機，主要是因為k線與成交量繪圖會讓記憶體使用量衝上去
             if (!(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)){
            index_array_layer_lin=1;
            if([[self.layerHost.hostedGraph sublayers] indexOfObject:layer_lin1L] == NSNotFound)
            {
                [array_layer_lin release];
                array_layer_lin=nil;
                array_layer_lin=[[NSMutableArray alloc] init];
                // [array_layer_lin autorelease];
                
                
                //第1列 最左邊 顯示 代號 與 名稱
                layer_lin1L =  [[CPTTextLayer alloc] init]  ;
                layer_lin1L.bounds = CGRectMake(0, 0, 20,50);
                
                CPTMutableTextStyle *textStyle1 = [CPTMutableTextStyle textStyle];
                textStyle1.color    =  [CPTColor whiteColor];
                textStyle1.fontSize  = 13;
                // textStyle1.textAlignment=CPTTextAlignmentCenter;
                
                layer_lin1L.textStyle=textStyle1;
                
                [array_layer_lin addObject:layer_lin1L];
                [self.layerHost.hostedGraph addSublayer:layer_lin1L];
                
                
                //第4列 最左邊 顯示 程式訊號 最多27行
                for (int m=1; m<27; m++) {
                    CPTTextLayer *layer_linL;
                    layer_linL = [[[CPTTextLayer alloc] init] autorelease];
                    layer_linL.bounds = CGRectMake(0, 7*m, 20,50);
                    
                    CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
                    textStyle.color    =  [CPTColor redColor];
                    textStyle.fontSize  = 13;
                    layer_linL.textStyle=textStyle;
                    
                    [array_layer_lin addObject:layer_linL];
                    [self.layerHost.hostedGraph addSublayer:layer_linL];
                }
                
                
                
                //第一列 最右邊 顯示 收盤價
                layer_lin1R =  [[CPTTextLayer alloc] init]  ;
                layer_lin1R.bounds = CGRectMake(-250, 5, 20,50);
                
                CPTMutableTextStyle *textStyle2l = [CPTMutableTextStyle textStyle];
                textStyle2l.color    =  [CPTColor orangeColor];
                textStyle2l.fontSize  = 13;
                
                layer_lin1R.textStyle=textStyle2l;
                [self.layerHost.hostedGraph addSublayer:layer_lin1R];
                
                //左邊 顯示最左邊的年份
                layer_year =  [[CPTTextLayer alloc] init]  ;
                if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
                    
                    //1024 *768 44
                    if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ){
                        layer_year.bounds = CGRectMake(0, 327, 50,50);
                    }
                    else{
                        layer_year.bounds = CGRectMake(0, 241, 50,50);
                    }
                    
                    
                    
                }
                else{
                    layer_year.bounds =  CGRectMake(0, 121, 50,50);
                    
                }
                
                
                
                CPTMutableTextStyle *textStyleYear = [CPTMutableTextStyle textStyle];
                textStyleYear.color    =  [CPTColor orangeColor];
                textStyleYear.fontSize=13;
                
                layer_year.textStyle=textStyleYear;
                [self.layerHost.hostedGraph addSublayer:layer_year];
                layer_year.text=@"2010";
                //==================
                
                //右邊 最接近日期
                layer_MonthDay = [[[CPTTextLayer alloc] init] autorelease];
                
                if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
                    
                    //1024 *768 44
                    
                    if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ) {
                        layer_MonthDay.bounds = CGRectMake(0,327, 50,50);
                        
                        
                        
                    }
                    else{
                        layer_MonthDay.bounds = CGRectMake( 0, 241, 50,50);
                        
                    }
                    
                    
                    
                    
                }
                else{
                    layer_MonthDay.bounds = CGRectMake(0, 121, 50,50);
                    
                }
                
                CPTMutableTextStyle *textStylemonthday = [CPTMutableTextStyle textStyle];
                textStylemonthday.color    =  [CPTColor orangeColor];
                textStylemonthday.fontSize=13;
                textStylemonthday.textAlignment=CPTTextAlignmentRight;
                //重要 關於設定 CPTTextLayer 的x,y
                //   僅可以設定  y
                //   所以只能用 最右邊或最左邊 或中間來設定 x軸位置 無法指定特定位置
                
                
                layer_MonthDay.textStyle=textStylemonthday;
                [self.layerHost.hostedGraph addSublayer:layer_MonthDay];
                
                
                
                
            }
            
            else {
                if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
                    
                    
                    
                    for (int k=0; k<[array_layer_lin count]; k++) {
                        [self.layerHost.hostedGraph addSublayer:[array_layer_lin objectAtIndex:k]];
                    }
                    // [array_layer_lin
                    [self.layerHost.hostedGraph addSublayer:layer_lin1R];
                    [self.layerHost.hostedGraph addSublayer:layer_year];
                    [self.layerHost.hostedGraph addSublayer:layer_MonthDay];
                    
                    //1024 *768 44
                    if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ) {
                        layer_year.bounds = CGRectMake(0, 327, 50,50);
                    }
                    else{
                        layer_year.bounds = CGRectMake(0, 241, 50,50);
                    }
                    if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ) {
                        layer_MonthDay.bounds = CGRectMake(0, 327, 50,50);
                    }
                    else{
                        layer_MonthDay.bounds = CGRectMake(0, 241, 50,50);
                    }
                    
                    
                    
                }
                
                
                
                for (int m=1; m<27; m++) {
                    CPTTextLayer *Acptx;
                    Acptx=[array_layer_lin objectAtIndex:m];
                    Acptx.text=@"";
                }
            }
        
        }
                       
             
        
            //[graph addPlot:pieChart];
            //[pieChart release];
            
            //標籤:走勢圖的滑動 啓動互動模式      
            CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
            plotSpace.allowsUserInteraction =NO ;        
            
            
            
            // NSLog(@"redrawchart_12" );
            plotSpace.delegate=self;
            NSDecimalNumber *high =[self HighPrice:stockdata startX:KBarSartLocation count:KBarLength];
            NSDecimalNumber *low = [self LowPrice:stockdata startX:KBarSartLocation count:KBarLength];
            NSDecimalNumber *volhigh = [self HighVolume:stockdata startX:KBarSartLocation count:KBarLength];
            //NSLog(@"redrawchart_13" );	
            
            Volrange=volhigh;	
            //+1主要是為了讓Ｋ線最右邊不會被切半
            plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromUnsignedInteger(KBarLength+1) ];
            //  NSLog(@"redrawchart_14" );
            //設定價格走勢圖的y區間位置
            // NSLog(@"high = %@, low = %@ ", high, low );
            NSDecimalNumber *length = [high decimalNumberBySubtracting:low];
            
            NSDecimalNumber *pricePlotSpaceDisplacementPercent = [NSDecimalNumber decimalNumberWithString:@"0.5"];
            
            NSDecimalNumber *lengthDisplacementValue = [length decimalNumberByMultiplyingBy:pricePlotSpaceDisplacementPercent]   ;
            
            NSDecimalNumber *lowDisplayLocation = [low decimalNumberBySubtracting:lengthDisplacementValue]  ;
            
            NSDecimalNumber *lengthDisplayLocation = [length decimalNumberByAdding:lengthDisplacementValue]  ;
            
            NSDecimalNumber *x_orthogonalCoordinate= [lowDisplayLocation decimalNumberByAdding:lengthDisplacementValue];
            
            x0=lowDisplayLocation;
            x1=x_orthogonalCoordinate;
            x2=high;
            xVolRange=lengthDisplacementValue ;
            //NSLog(@"redrawchart_2" );
            //NSLog(@"redrawchart3");	
            plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:[lowDisplayLocation decimalValue] length:[lengthDisplayLocation decimalValue]];
            
            // Axes
            CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
            
            //x
            CPTXYAxis *x = axisSet.xAxis;
            //x坐標軸起始位置
            x.orthogonalCoordinateDecimal =[x_orthogonalCoordinate decimalValue];  //x 軸放在y軸的位置
            
            // Grid line styles
            CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
            majorGridLineStyle.lineWidth = 0.5;
            majorGridLineStyle.lineColor = [[CPTColor colorWithGenericGray:0.4] colorWithAlphaComponent:0.75];
            
            x.majorGridLineStyle = majorGridLineStyle;
            x.majorIntervalLength =CPTDecimalFromInteger(10);
            x.minorTicksPerInterval = 0;
            
            //計算間隔多少Ｋ線要呈現日期
            //int showKnumber;
            //showKnumber=6; //走勢圖上秀出6根ＫK線
            int kbarnumber;
            kbarnumber=KBarLength/6;
            
            
            //將Ｘ軸坐標軸改為自設日期
            NSMutableArray *customTickLocations ;
            customTickLocations=[[NSMutableArray alloc] init];
            
            for (int i=1; i<6; i++) {
                
                if (i*kbarnumber<[stockdata.financialData count]) {
                    [customTickLocations addObject:[NSDecimalNumber numberWithInt:i*kbarnumber]];	
                }	
                
                
            }
            
            
            
            NSMutableArray *xAxisLabels ;
            xAxisLabels=[[NSMutableArray alloc] init];
            for (int i=1; i<6; i++) {
                if (i*kbarnumber<[stockdata.financialData count]) {		
                    [xAxisLabels addObject:[self LableDateString:KBarSartLocation+i*kbarnumber]];	
                }
            }	
            
            layer_year.text=[self LableDateStringYear:KBarSartLocation+0];
            layer_MonthDay.text=[self LableDateString:KBarSartLocation+KBarLength-1];
            
            NSUInteger labelLocation = 0;
            NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
            for (NSNumber *tickLocation in customTickLocations) {
                CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText: [xAxisLabels objectAtIndex:labelLocation++] textStyle:axisSet.xAxis.labelTextStyle];
                newLabel.tickLocation = [tickLocation decimalValue];
                newLabel.offset = axisSet.xAxis.labelOffset + axisSet.xAxis.majorTickLength;
                newLabel.offset =  0.0;
                [customLabels addObject:newLabel];
                [newLabel release];
            }
            [xAxisLabels release];
            x.labelingPolicy = CPTAxisLabelingPolicyNone;
            
            //當使用CPAxisLabelingPolicyNone 可以顯示格線
            axisSet.xAxis.majorTickLocations = [NSSet setWithArray:	customTickLocations] ;
            
            axisSet.xAxis.axisLabels =  [NSSet setWithArray:customLabels];		
            
            //y
            CPTXYAxis *y = axisSet.yAxis;
            //將Ｘ軸坐標軸改為自設日期
            
            
            NSMutableArray *y_customTickLocations =[[NSMutableArray alloc] init];		
            NSMutableArray *y_AxisLabels=[[NSMutableArray alloc] init];	
            NSDecimalNumber *ylength = [length decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:@"4"]];
            
            int y_offset;
            if ([low floatValue]<=10) {
                y_offset=-30;
            }
            else {
                y_offset=-35;
            }
            
            
            for (int y1=1; y1< 4; y1++) {
                [y_customTickLocations addObject:[low decimalNumberByAdding:[ylength decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",y1]] ] ]];	
                
                
            }
            
            for (int y1=1; y1< 4; y1++) {
                //[y_AxisLabels addObject:[ [low decimalNumberByAdding:[ylength decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",y1]] ] ] floatValue ]];	
                
                if ([low floatValue]>=100) {
                    [y_AxisLabels addObject: [NSString stringWithFormat:@"%0.0f",[ [low decimalNumberByAdding:[ylength decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",y1]] ] ] floatValue ]]];	
                    
                }
                else {
                    //NSLog(@"wwwwwww=%@", [NSString stringWithFormat:@"%0.1f",[ [low decimalNumberByAdding:[ylength decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",y1]] ] ] floatValue ]]);
                    [y_AxisLabels addObject: [NSString stringWithFormat:@"%0.1f",[ [low decimalNumberByAdding:[ylength decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%i",y1]] ] ] floatValue ]]];	
                    
                }			
                
            }
            
            //NSArray *y_AxisLabels = [NSArray arrayWithObjects:[high stringValue],[low stringValue],nil];
            
            //NSLog(@"redrawchart_5" );	
            NSUInteger y_labelLocation = 0;
            NSMutableArray *y_customLabels = [NSMutableArray arrayWithCapacity:[y_AxisLabels count]];
            for (NSDecimalNumber *tickLocation in y_customTickLocations) {
                
                CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText: [y_AxisLabels objectAtIndex:y_labelLocation ] textStyle:axisSet.yAxis.labelTextStyle];
                y_labelLocation=y_labelLocation+1;
                
                newLabel.tickLocation = [tickLocation decimalValue];
                newLabel.offset = y_offset;
                [y_customLabels addObject:newLabel];
                [newLabel release];
            }
            [y_AxisLabels release];
            
            
            y.labelingPolicy = CPTAxisLabelingPolicyNone;
            axisSet.yAxis.axisLabels =  [NSSet setWithArray:y_customLabels];	
            axisSet.yAxis.majorGridLineStyle=majorGridLineStyle;
            
            //當使用CPAxisLabelingPolicyNone 可以顯示格線
            
            NSMutableSet *yc;
            yc=[y_customTickLocations mutableCopy];
            axisSet.yAxis.majorTickLocations=yc;//y_customTickLocations;
            
            //消除所有的曲線
            for (CPTPlot *plott in [graph allPlots])
                [graph removePlot:plott];
            
            
            //設定蠟燭線 plot
            //設定平盤顏色
            CPTMutableLineStyle *unchange_LineStyle = [CPTMutableLineStyle lineStyle];
            unchange_LineStyle.lineColor = [CPTColor whiteColor];
            unchange_LineStyle.lineWidth = 1.0f;
            
            //設定上漲下跌顏色
            CPTColor *cupcolor;
            CPTColor *cdowncolor;
            //上漲
            if ([[prefs objectForKey:@"upColor"] isEqualToString:@"greenColor" ] ) {
                cupcolor=[CPTColor colorWithComponentRed:(123/255.f) green:(237/255.f) blue:(11/255.f) alpha:1];
            } 
            else if ([[prefs objectForKey:@"upColor"] isEqualToString:@"redColor" ] ) {
                cupcolor=[CPTColor redColor];
            }         
            //下跌
            if ([[prefs objectForKey:@"downColor"] isEqualToString:@"redColor" ] ) {
                cdowncolor=[CPTColor redColor];
            } 
            else if ([[prefs objectForKey:@"downColor"] isEqualToString:@"greenColor" ] ) {
                cdowncolor=[CPTColor colorWithComponentRed:(123/255.f) green:(237/255.f) blue:(11/255.f) alpha:1];
            }             
            
            
            CPTMutableLineStyle *increase_LineStyle = [CPTMutableLineStyle lineStyle];
             increase_LineStyle.lineColor = cupcolor;
             increase_LineStyle.lineWidth = 1.0f;            
             
            CPTMutableLineStyle *decrease_LineStyle = [CPTMutableLineStyle lineStyle];
            decrease_LineStyle.lineColor = cdowncolor;
            decrease_LineStyle.lineWidth = 1.0f;             
          
            //上漲的實體棒中間採用中空方式
            CPTFill *increase_Fill ;
            CPTFill *decrease_Fill  ;            
           
            //標記:判斷是MESA或LF
            NSString *DisplayName;
            DisplayName=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];     
            NSArray * DisplayName_array=[ DisplayName componentsSeparatedByString:@"_"];    
            
            if ([DisplayName_array count]>=3) {
                if ([[DisplayName_array objectAtIndex:2] isEqualToString:@"MESA"] ) {
                    //MESA
                     increase_Fill=[(CPTFill *)[CPTFill alloc] initWithColor:[CPTColor clearColor]];
                     decrease_Fill = [(CPTFill *)[CPTFill alloc] initWithColor:cdowncolor];            
                    
                                       
                }
                else{
                    //開始LF
                    increase_Fill=[(CPTFill *)[CPTFill alloc] initWithColor:cupcolor];
                    decrease_Fill = [(CPTFill *)[CPTFill alloc] initWithColor:cdowncolor];            
                    
                                       
                }
            }
 
            
             
            
            CPTTradingRangePlot *ohlcPlot =  [[CPTTradingRangePlot alloc] initWithFrame:graph.bounds]  ;
            ohlcPlot.identifier = @"OHLC";
            ohlcPlot.delegate=self;
            
            //設定平盤
            ohlcPlot.lineStyle = unchange_LineStyle;
            
            //設定漲跌幅
            ohlcPlot.increaseLineStyle=increase_LineStyle; //四周框線
            ohlcPlot.increaseFill=increase_Fill;    //實體棒顏色
            ohlcPlot.decreaseLineStyle=decrease_LineStyle;
            ohlcPlot.decreaseFill=decrease_Fill;              
            
            ohlcPlot.stickLength = 5.0f;
            ohlcPlot.dataSource = self;
            
            ohlcPlot.plotStyle = CPTTradingRangePlotStyleCandleStick; //CPTradingRangePlotStyleOHLC;
            
            
                   
            
            
            //[ohlcPlot upWithColor:cupcolor downcolor: cdowncolor];
            //[ohlcPlot upWithColor:[CPColor redColor] downcolor:[CPColor colorWithComponentRed:0 green:255 blue:0 alpha:0]];
            
            [graph addPlot:ohlcPlot];		
        [ohlcPlot release];
        
            
              
            //建立笑傲曲線走勢圖資料
            [plotIdentfy release];
            plotIdentfy=  [[NSMutableArray alloc] init] ;	
            
            
            NSMutableArray *pre;
            pre=dataForPlot_Array;
            
            // [dataForPlot_Array release];
            dataForPlot_Array=  [[NSMutableArray alloc] init] ;
            //[pre release];
             NSAutoreleasePool * pool_1 = [[NSAutoreleasePool alloc] init];
            if (pre!=nil) {
                
                for (NSMutableArray *aa in pre) {
                    [aa removeAllObjects];
                    
                    [aa release];
                }
                //[pre release];
                
            }
             [pool_1 release];
             
            
        
            NSMutableArray *bbb;
            bbb=[stockdata.aParaObject CaArray_LF];
            for (int j=0; j<[bbb count]; j++) {
              
                if([[[bbb objectAtIndex:j] valueForKey:@"isShow"] boolValue]){
                    NSMutableDictionary * last_fdata;
                    
                     
                    last_fdata=[self buildLF:[[bbb objectAtIndex:j] valueForKey:@"idendfiler"]
                                  blineColor:[[bbb objectAtIndex:j] valueForKey:@"Blinecolor"]
                                  slineColor:[[bbb objectAtIndex:j] valueForKey:@"Slinecolor"] 
                                   blinewith:[[[bbb objectAtIndex:j] valueForKey:@"Blinewith"] floatValue]
                                   slinewith:[[[bbb objectAtIndex:j] valueForKey:@"Slinewith"] floatValue]
                                ];
                     
                    if ([(NSNumber *)[prefs objectForKey:@"isSowIndicatorNumber"] boolValue]==YES) {
                        // 左邊註解
                        [self showLeft_layer: [bbb objectAtIndex:j] fdata:last_fdata graph_line:[array_layer_lin objectAtIndex:index_array_layer_lin]];
                        if (index_array_layer_lin+1<[array_layer_lin count]) {
                            index_array_layer_lin=index_array_layer_lin+1;			
                        }				
                    }			
                     
                    
                    
                }		
            }		
            
            
             
            //建立移動均線
            NSMutableArray *aaa;
            aaa=[stockdata.aParaObject CaArray_MovingAverage];
            for (int j=0; j<[aaa count]; j++) {
                if([[[aaa objectAtIndex:j] valueForKey:@"isShow"] boolValue]){
                    
                    [graph addPlot:[self addnewplot:graph identifier:[[aaa objectAtIndex:j] valueForKey:@"idendfiler"] andlinecolor:[[aaa objectAtIndex:j] valueForKey:@"linecolor"]  andLineWith:[[[aaa objectAtIndex:j] valueForKey:@"linewith"] floatValue]]];
                    
                    if ([(NSNumber *)[prefs objectForKey:@"isSowIndicatorNumber"] boolValue]==YES) {
                        // 左邊註解
                        [self showLeft_layer: [aaa objectAtIndex:j] fdata:[stockdata.financialData_Calcuate objectAtIndex:KBarSartLocation+KBarLength-1 ] graph_line:[array_layer_lin objectAtIndex:index_array_layer_lin]];
                    }
                    
                    
                }		
            }	
        
             
            //建立ＭＥＳＡ
            NSMutableArray *ddd;
            ddd=[stockdata.aParaObject CaArray_MESA];
            for (int j=0; j<[ddd count]; j++) {
                if([[[ddd objectAtIndex:j] valueForKey:@"isShow"] boolValue]){
                    NSString *idents;
                    idents =(NSString *)[[ddd objectAtIndex:j] valueForKey:@"idendfiler"];
                    
                    [graph addPlot:[self addnewplot:graph identifier:[idents stringByAppendingString:@"FAMA"] andlinecolor:[[ddd objectAtIndex:j] valueForKey:@"FAMAlinecolor"]  andLineWith:[[[ddd objectAtIndex:j] valueForKey:@"FAMAlinewith"] floatValue]]];
                    [graph addPlot:[self addnewplot:graph identifier:[idents stringByAppendingString:@"MAMA"] andlinecolor:[[ddd objectAtIndex:j] valueForKey:@"MAMAlinecolor"]  andLineWith:[[[ddd objectAtIndex:j] valueForKey:@"MAMAlinewith"] floatValue]]];
                    
                    if ([(NSNumber *)[prefs objectForKey:@"isSowIndicatorNumber"] boolValue]==YES) {
                        // 左邊註解
                        [self showLeft_layer: [ddd objectAtIndex:j] fdata:[stockdata.financialData_Calcuate objectAtIndex:KBarSartLocation+KBarLength-1 ] graph_line:[array_layer_lin objectAtIndex:index_array_layer_lin]];
                        
                    }
                    
                    
                    
                }		
            }	
            
            NSMutableArray *eee;
            eee=[stockdata.aParaObject CaArray_xMESA];	
            
            NSLog(@"redrawchart_9" );
            if ( [[[eee objectAtIndex:0] valueForKey:@"isShow"] boolValue] ) {	
                [graph addPlot:[self addnewplot:graph identifier:@"aCmesa1_mama" andlinecolor: [[eee objectAtIndex:0] valueForKey:@"MAMAlinecolor"]   andLineWith:[[[eee objectAtIndex:0] valueForKey:@"FAMAlinewith"] floatValue]]];
                [graph addPlot:[self addnewplot:graph identifier:@"aCmesa1_fama" andlinecolor: [[eee objectAtIndex:0] valueForKey:@"FAMAlinecolor"]   andLineWith:[[[eee objectAtIndex:0] valueForKey:@"MAMAlinewith"] floatValue]]];
                // 左邊註解
                //[self showLeft_layer: [eee objectAtIndex:j] fdata:[stockdata.financialData_Calcuate objectAtIndex:KBarSartLocation+KBarLength-1 ] graph_line:[array_layer_lin objectAtIndex:index_array_layer_lin]];
            }
            //NSLog(@"redrawchart_91" );
            if ( [[[eee objectAtIndex:1] valueForKey:@"isShow"] boolValue] ) {		
                [graph addPlot:[self addnewplot:graph identifier:@"aCmesa2_mama" andlinecolor: [[eee objectAtIndex:1] valueForKey:@"MAMAlinecolor"]   andLineWith:[[[eee objectAtIndex:1] valueForKey:@"FAMAlinewith"] floatValue]]];
                [graph addPlot:[self addnewplot:graph identifier:@"aCmesa2_fama" andlinecolor: [[eee objectAtIndex:1] valueForKey:@"FAMAlinecolor"]   andLineWith:[[[eee objectAtIndex:1] valueForKey:@"MAMAlinewith"] floatValue]]];
                // 左邊註解
                //[self showLeft_layer: [eee objectAtIndex:j] fdata:[stockdata.financialData_Calcuate objectAtIndex:KBarSartLocation+KBarLength-1 ] graph_line:[array_layer_lin objectAtIndex:index_array_layer_lin]];
                
            }
            //建立kd
            //NSLog(@"redrawchart_92" );	
            NSMutableArray *KKK;
            KKK=[stockdata.aParaObject CaArray_KD];
            
            if ( [[[KKK objectAtIndex:0] valueForKey:@"isShow"] boolValue] ) {	
                
                [graph addPlot:[self addnewplot:graph identifier:@"CKD_K" andlinecolor:[[KKK objectAtIndex:0] valueForKey:@"Klinecolor"] andLineWith:[[[KKK objectAtIndex:0] valueForKey:@"Klinewith"] floatValue]]];
                [graph addPlot:[self addnewplot:graph identifier:@"CKD_D" andlinecolor:[[KKK objectAtIndex:0] valueForKey:@"Dlinecolor"]   andLineWith:[[[KKK objectAtIndex:0] valueForKey:@"Dlinewith"] floatValue]]];
                
                if ([(NSNumber *)[prefs objectForKey:@"isSowIndicatorNumber"] boolValue]==YES) {
                    // 左邊註解
                    [self showLeft_layer: [KKK objectAtIndex:0] fdata:[stockdata.financialData_Calcuate objectAtIndex:KBarSartLocation+KBarLength-1 ] graph_line:[array_layer_lin objectAtIndex:index_array_layer_lin]];
                    
                }		
                
            }
            
            //成交量====================	
            
            NSMutableArray *vvv;
            vvv=[stockdata.aParaObject CaArray_volume];
            if ( [[[vvv objectAtIndex:0] valueForKey:@"isShow"] boolValue] ) {	
                CPTBarPlot *volumePlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor redColor] horizontalBars:NO];
                volumePlot.dataSource = self;
                CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
                lineStyle.lineColor =[[vvv objectAtIndex:0] valueForKey:@"lineColor"];                 
                
                volumePlot.lineStyle= lineStyle;
                volumePlot.fill = nil; 
               // volumePlot.barWidth =CPTDecimalFromFloat([[[vvv objectAtIndex:0] valueForKey:@"barWidth"] floatValue]);  
                volumePlot.barWidth =CPTDecimalFromFloat(0.5); 
                volumePlot.identifier = [[vvv objectAtIndex:0] valueForKey:@"idendfiler"];	
                volumePlot.delegate=self;
                //volume 的基底位置 因為 x0 的位置有可能為負的 所以必須調整基底位置
                float xx0;
                xx0=[x0 floatValue]; 
                volumePlot.baseValue=CPTDecimalFromFloat(xx0);	 
                [graph addPlot:volumePlot ];
                
                if ([(NSNumber *)[prefs objectForKey:@"isSowIndicatorNumber"] boolValue]==YES) {
                    // 左邊註解
                    [self showLeft_layer: [vvv objectAtIndex:0] fdata:[stockdata.financialData_Calcuate objectAtIndex:KBarSartLocation+KBarLength-1 ] graph_line:[array_layer_lin objectAtIndex:index_array_layer_lin]];
                    
                }				
                
                
            }		
            
            
            
            //詳細資料設定
            [self graph_Setup_Detail:KBarSartLocation+KBarLength-1];
            
            
        
             [graph reloadData];
        
            
            
            //標記:繪圖結束後的最後位置 1.StockGrapth-redrawchart
            NSLog(@"redrawchart_end" );
            [(AppDelegate * )AppleDeglate setCan_use_graph_setup:@"YES" ];              
            
            [[self navigationItem] setTitle:stockdata.symbol];		
            
            [segmetnctl setUserInteractionEnabled:YES];	
            
            //標記:tabBarController 暫停使用 (繪圖結束後 開啓使用)   
            [(AppDelegate * )AppleDeglate Set_tabBarController_Enable];        
        
            self.navigationItem.hidesBackButton=NO;        
      
             
    
    
    }
         	     
        
   
}

#pragma mark -
#pragma mark  設定走勢圖上的詳細資料
-(void)graph_Setup_Detail:(int)lastindex{
	
   
    //標記:是否移除交易所碼        
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	
    
    if ([[prefs objectForKey:@"isRemoveExchangeCode"] boolValue]==YES) {
        //字串分割
        NSArray *code_exchange_Array = [stockdata.symbol componentsSeparatedByString:@"."];
        if ([code_exchange_Array count]==2) {
            
           layer_lin1L.text= [[[code_exchange_Array objectAtIndex:0] stringByAppendingString:@" "] stringByAppendingString:stockdata.name]  ;     
        }
        else{
            layer_lin1L.text= [[stockdata.symbol stringByAppendingString:@" "] stringByAppendingString:stockdata.name]  ;
            
        }
        
    }
    else {
         layer_lin1L.text= [[stockdata.symbol stringByAppendingString:@" "] stringByAppendingString:stockdata.name]  ;
    }                   
    
	if (lastindex<[stockdata.financialData count]) {
		NSArray *financialData = stockdata.financialData;
		NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:lastindex];
		NSDecimalNumber *theclose= [fData objectForKey:@"close"];	
		 
		 	
		layer_lin1L.text=[layer_lin1L.text stringByAppendingString:[NSLocalizedString(@"  close:",@"  close:") stringByAppendingString: [NSString stringWithFormat:@"%0.02f",[theclose floatValue]] ]];		
	}
	 
	
	
}


#pragma mark -
#pragma mark  取的資料物件方法
-(void)get_stockdata:(DataObject *)astockdata{
       
    NSLog(@"get_stockdata");
     stockdata=astockdata;
      //NSLog(@"aaaaa finance account=%i",  [stockdata.financialData count]);
}

#pragma mark -
#pragma mark  笑傲走勢圖方法
-(NSMutableDictionary *)buildLF:(NSString *)identfilers 
	blineColor:(CPTColor *)blinecolor
	slineColor:(CPTColor *)slinecolor
	 blinewith:(CGFloat)bwlinewith
	 slinewith:(CGFloat)swlinewith
{
	 
	
	NSArray *financialData =  stockdata.financialData_Calcuate ;
	NSMutableArray *contentArray=nil ;
	NSMutableArray *scontentArray=nil ;
	
	 int bout_count,sout_count;
	 bout_count=0;
	 sout_count=0;
	
	float LF_bout,LF_sout;
	float LF_bout_1,LF_sout_1;
	int LF_b,LF_s;
	int LF_b_1,LF_s_1; //前ㄧ期買賣狀態
	
	BOOL haveB,haveS;
	haveB=NO;
	haveS=NO;
	
	LF_b_1=0;
	LF_s_1=0;
	LF_bout_1=0;
	LF_sout_1=0;
 
 
	NSMutableDictionary *last_fData;
	last_fData=[[[NSMutableDictionary alloc] init] autorelease];
	
	 
    for (int i=0;  i<KBarLength  ; i++) {
	 
		//避免資料位置錯誤
		//if (KBarSartLocation+i>=[financialData count]) {
			//return;
		//}
	//	NSLog(@"a1");
		//取出當前資料
	    if (KBarSartLocation+i<[financialData count]) {
		 
		NSMutableDictionary *fData = (NSMutableDictionary *)[financialData objectAtIndex:KBarSartLocation+i];
	    
	//	NSLog(@"a2");
		
		LF_b=[[fData objectForKey:[identfilers stringByAppendingString:@"_b"]] intValue];
	    LF_s=[[fData objectForKey:[identfilers stringByAppendingString:@"_s"]] intValue];
	    LF_bout=[[fData objectForKey:[identfilers stringByAppendingString:@"_bout"]] floatValue];
	    LF_sout=[[fData objectForKey:[identfilers stringByAppendingString:@"_sout"]] floatValue];
	    
		//  NSLog(@"i=%i count=%i bout=%f sout=%f",i,KBarLength,LF_bout,LF_sout);	
		if (i==KBarLength-1) {
			last_fData=  fData   ;
		}	
			
		//第ㄧ次建立買方線
		if ((LF_b==1 && LF_b_1==0) || (i==0 && LF_b==1) ) {
			haveB=YES;
			bout_count=bout_count+1;
			[plotIdentfy addObject:[identfilers stringByAppendingString:[NSString stringWithFormat:@"bout=%i",bout_count]]];
			 
            
           // [contentArray release];
            contentArray= [[NSMutableArray alloc] init]  ;
			
			NSNumber *x =  [NSNumber numberWithFloat: i ];
			NSNumber *y = [NSNumber numberWithFloat:LF_bout];
			[contentArray  addObject: [NSMutableDictionary dictionaryWithObjectsAndKeys: x  ,  @"x" , y  ,  @"y"   ,nil]  ];
			 
		 }
	    //買方線資料持續加入
		if (LF_b==1 && LF_b_1==1) {
			
			NSNumber *x = [NSNumber numberWithFloat: i ];
			NSNumber *y = [NSNumber numberWithFloat:LF_bout];
            
			[contentArray  addObject: [ NSMutableDictionary   dictionaryWithObjectsAndKeys: x  ,  @"x"  , y  ,  @"y"   ,nil]  ];
             
            
		}		
		//最後買方線退出結束
		if (LF_b==0 && LF_b_1==1) {
			
			//只紀錄到前ㄧ期
			NSNumber *x = [NSNumber numberWithFloat: i-1 ];
			NSNumber *y = [NSNumber numberWithFloat:LF_bout_1];
			[contentArray  addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys: x  , @"x",  y  , @"y"  ,nil]];
		 
			[ dataForPlot_Array addObject: contentArray  ];
			//[contentArray release];
			//contentArray=nil;
			[graph addPlot:[self addnewplot:graph identifier:[identfilers stringByAppendingString:[NSString stringWithFormat:@"bout=%i",bout_count]] andlinecolor:blinecolor andLineWith:bwlinewith]];
		    haveB=NO;
            
                      
		}
		
		//第ㄧ次建立賣方線
		if ((LF_s==1 && LF_s_1==0) || (i==0 && LF_s==1)) {
			haveS=YES;
			sout_count=sout_count+1;
			[plotIdentfy addObject:[identfilers stringByAppendingString:[NSString stringWithFormat:@"sout=%i",sout_count]]];
            
           // [scontentArray release];
			scontentArray= [[NSMutableArray alloc] init]  ;
			
			NSNumber *x = [NSNumber numberWithFloat: i ];
			NSNumber *y = [NSNumber numberWithFloat:LF_sout];
			[scontentArray  addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys: x  , @"x",  y  , @"y"  ,nil]];
			 
		}
		//賣方線資料持續加入
		if ((LF_s==1 && LF_s_1==1)  ) {
			
			NSNumber *x = [NSNumber numberWithFloat: i ];
			NSNumber *y = [NSNumber numberWithFloat:LF_sout];
			[scontentArray  addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys: x  , @"x",  y  , @"y"  ,nil]];
			 
		}		
		//最後賣方線退出結束
		if (LF_s==0 && LF_s_1==1) {
			
			//只紀錄到前ㄧ期
			NSNumber *x = [NSNumber numberWithFloat: i-1 ];
			NSNumber *y = [NSNumber numberWithFloat:LF_sout_1];
			[scontentArray  addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys: x  , @"x",  y , @"y"  ,nil]];
			
			[ dataForPlot_Array addObject: scontentArray  ];
			 //[scontentArray release];
			//scontentArray=nil;
			[graph addPlot:[self addnewplot:graph identifier:[identfilers stringByAppendingString:[NSString stringWithFormat:@"sout=%i",sout_count]] andlinecolor:slinecolor andLineWith:swlinewith]];
	        haveS=NO;
           
		}
	//	NSLog(@"a3");
		
		//紀錄前一筆資料
		LF_b_1=LF_b;
		LF_s_1=LF_s;
		LF_bout_1=LF_bout;
		LF_sout_1=LF_sout;
		
                
        }
	  
   }
		 	
	//因為最後一筆線需要另外加入判斷
	if (contentArray != nil && haveB==YES) {
		 [ dataForPlot_Array addObject: contentArray  ];
         
         [contentArray release];
		 [graph addPlot:[self addnewplot:graph identifier:[identfilers stringByAppendingString:[NSString stringWithFormat:@"bout=%i",bout_count]] andlinecolor:blinecolor andLineWith:bwlinewith]];
		
		
	}
    
	if (scontentArray != nil && haveS==YES) {
		 [ dataForPlot_Array addObject: scontentArray  ];
         [scontentArray release];
		 [graph addPlot:[self addnewplot:graph identifier:[identfilers stringByAppendingString:[NSString stringWithFormat:@"sout=%i",sout_count]] andlinecolor:slinecolor andLineWith:swlinewith]];
	}
   
	 
	
    
    return last_fData;
}

#pragma mark -
#pragma mark  直線屬性新增設定

-(CPTScatterPlot *)addnewplot:(CPTXYGraph *)grapha identifier:(NSString *)ident andlinecolor:(CPTColor *)linecolor andLineWith:(CGFloat)linef {
	CPTScatterPlot *dataSourceLinePlot  = [[[CPTScatterPlot alloc] init] autorelease];
	dataSourceLinePlot.identifier = ident;
    CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
    lineStyle.lineColor =linecolor; 
    lineStyle.lineWidth=linef;
    dataSourceLinePlot.dataLineStyle  = lineStyle;
	 
	//dataSourceLinePlot.dataLineStyle.dashPattern = [NSArray arrayWithObjects:[NSNumber numberWithFloat:1.0f], [NSNumber numberWithFloat:0.0f], nil];
	dataSourceLinePlot.dataSource = self;	
	return dataSourceLinePlot;
	
}
 




#pragma mark -
#pragma mark  走勢圖資料匯入委託方法
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot{
	if ([plotIdentfy indexOfObject:plot.identifier]!=NSNotFound) {
		//笑傲曲線		
		NSUInteger  idex_of_identifier;
		idex_of_identifier=[plotIdentfy indexOfObject:plot.identifier];
		return [[dataForPlot_Array objectAtIndex:  idex_of_identifier] count];	
	}	
	else {	
		//return stockdata.financialData.count;
		
		 return KBarLength; //自設Ｋ線數量
	
	}
	
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
	 
     
	//NSLog(@"plot=%@ index=%i",plot.identifier,index);
	NSDecimalNumber *num = [NSDecimalNumber zero];		
    
     
	if (KBarSartLocation+ index>=[stockdata.financialData count]) {
        return num;
    }
    
    if ([plot isKindOfClass:[CPTBarPlot class]] ) {
         
        //成交量 用是否為柱狀圖判斷
        switch ( fieldEnum ) {
            case CPTBarPlotFieldBarLocation:
                num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index ];
                break;
            case CPTBarPlotFieldBarTip:
                ;NSArray *financialData = stockdata.financialData;
                NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:KBarSartLocation+ index  ];
                
                
                     if ( [Volrange isEqualToNumber:[NSDecimalNumber zero] ]) {
                        Volrange=[NSDecimalNumber decimalNumberWithString:@"1"];
                    }
                    
                    num= [x0 decimalNumberByAdding: [xVolRange decimalNumberByMultiplyingBy:[ [self turnNSDecimalNumber: [fData objectForKey:@"volume"]]     decimalNumberByDividingBy:Volrange]]];
                                    
                
                
                break;
        }
        //====================
    }
    else
    {
        //如果不是柱狀圖 就是k線圖
        
        if ([plotIdentfy indexOfObject:plot.identifier]!=NSNotFound)
        {
             
            //笑傲曲線
            NSUInteger  idex_of_identifier;
            idex_of_identifier=[plotIdentfy indexOfObject:plot.identifier];
            NSNumber *num = [[[dataForPlot_Array objectAtIndex:  idex_of_identifier] objectAtIndex:index] valueForKey:(fieldEnum == CPTScatterPlotFieldX ? @"x" : @"y" )];
            if ( fieldEnum == CPTScatterPlotFieldY )
            {
                
                num = [NSNumber numberWithDouble:[num doubleValue]];
                //NSLog(@"%@",[num stringValue]);
            }
            return num;
            
        }
        
        //利用下面的轉化方法 可以將plot.identifier 轉成NSString 使用
        //移動均線的資料取出
        
        else if([(NSString *)plot.identifier hasPrefix:@"Caverage"]){
             
            NSArray *financialData =  stockdata.financialData_Calcuate  ;
            NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:KBarSartLocation+index];
            
            
            if ( fieldEnum == CPTScatterPlotFieldY )
            {
                num = [fData objectForKey:plot.identifier];
                //num = [fData objectForKey:@"LF_bout"];
                
            }
            else if(fieldEnum== CPTTradingRangePlotFieldX){
                num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index  ];
            }
            return num;
            
        }
        
        else if([(NSString *)plot.identifier hasPrefix:@"Cmesa"]  ){
             
            
            NSArray *financialData =  stockdata.financialData_Calcuate  ;
            NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:KBarSartLocation+index];
            if ( fieldEnum == CPTScatterPlotFieldY )
            {
                num = [fData objectForKey:plot.identifier];
                
            }
            else if(fieldEnum== CPTTradingRangePlotFieldX){
                num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index  ];
            }
            return num;
            
        }
        
        else if( [(NSString *)plot.identifier hasPrefix:@"aCmesa"]){
             
            //NSLog((NSString *)plot.identifier);
            NSArray *financialData =  stockdata.financialData_Calcuate  ;
            NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:KBarSartLocation+index];
            if ( fieldEnum == CPTScatterPlotFieldY )
            {
                num = [fData objectForKey:plot.identifier];
            }
            else if(fieldEnum== CPTTradingRangePlotFieldX){
                num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index  ];
            }
            return num;
            
        }
        
        else if([(NSString *)plot.identifier hasPrefix:@"CKD"]){
             
            
            NSArray *financialData =  stockdata.financialData_Calcuate  ;
             
            //NSLog(@"KBarSartLocation=%i index=%i count=%i",KBarSartLocation,index,[financialData count]);
            NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:KBarSartLocation+index];
             
            if ( fieldEnum == CPTScatterPlotFieldY )
            {
                 
                num = [fData objectForKey:plot.identifier];
                
                NSDecimalNumber *xKDRange;
                
                xKDRange=[NSDecimalNumber decimalNumberWithString:@"100"];
                 
                // NSLog(error);
                
                if ([fData objectForKey:plot.identifier] != nil){
                    
                    //判斷NSDecimalNumber 是否為Nan
                    if ( !([fData objectForKey:plot.identifier] ==[NSDecimalNumber notANumber])  ) {
                         
                        num= [x0 decimalNumberByAdding: [xVolRange decimalNumberByMultiplyingBy:[   [fData objectForKey:plot.identifier]     decimalNumberByDividingBy:xKDRange]]];
                    }
                }
                
                
                                 
            }
            else if(fieldEnum== CPTTradingRangePlotFieldX){
                                 
                num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index  ];
            }
            return num;		
            
        }				
        
        else
        {   		
            
           
            //k線圖
            NSArray *financialData = stockdata.financialData;
            NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:KBarSartLocation+index];
            
            switch ( fieldEnum )
            {
                case CPTTradingRangePlotFieldX:
                    num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index  ];
                    break;
                case CPTTradingRangePlotFieldClose:
                    num = [fData objectForKey:@"close"];
                    break; 
                case CPTTradingRangePlotFieldHigh:
                    num = [fData objectForKey:@"high"];
                    break;             
                case CPTTradingRangePlotFieldLow:
                    num = [fData objectForKey:@"low"];
                    break; 
                case CPTTradingRangePlotFieldOpen:
                    num = [fData objectForKey:@"open"];
                    break; 
            }	
        }
    }
      
    
    return num;
		  	  
	   
	   
    
   
 
	
}
#pragma mark -
#pragma mark  走勢圖-買賣訊號
//此段程式會影響table cell滑動的速度 主要是因為他將呼叫所有datalable 會駛速度將慢 
 
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index{
   
    //標記:是否顯示技術指標上的買賣訊號         
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	
    if ([[prefs objectForKey:@"isShowBuySellSignal"] boolValue]==NO) {
        //因選擇不顯示訊號所以直接跳出
        return  (id)[NSNull null];
    }                
    
    // 定义一个白色的 TextStyle
    // NSLog(@"plot=%@ index=%i",plot.identifier,index);
    NSMutableArray *dddA;
    dddA=[stockdata.aParaObject CaArray_MESA];    
    
    for (int j=0; j<[dddA count]; j++) {
        
        if([[[dddA objectAtIndex:j] valueForKey:@"isShow"] boolValue]){
            
            //NSString *idents;
            //idents =(NSString *)[[dddA objectAtIndex:j] valueForKey:@"idendfiler"];
            
            
        }
    }        
    
    
    NSArray *financialData =  stockdata.financialData_Calcuate  ;    
    
    int enterday; //隔幾日進場 0:當日 1:隔日 2:隔2日
    enterday=1; //隔日進場
    
    if ([(NSString *)plot.identifier hasPrefix:@"OHLC"] && index > (0 +enterday)     ) {
       
        NSMutableArray *para_MESA ;
        para_MESA=[stockdata.aParaObject CaArray_MESA];
       
        NSMutableArray *para_LF ;
        para_LF=[stockdata.aParaObject CaArray_LF];
        
        BOOL bsignal;
        BOOL ssignal;
        
        int bcount;
        int scount;
      
        bcount=0;
        scount=0;
        
        bsignal=NO;
        ssignal=NO;
        //MESA
        for (int j=0; j<[para_MESA count]; j++) {
            
            if([[[para_MESA objectAtIndex:j] valueForKey:@"isShow"] boolValue]){
                
                NSString *idents;
                idents =(NSString *)[[para_MESA objectAtIndex:j] valueForKey:@"idendfiler"];    
                
                                
                NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:KBarSartLocation+index-enterday ];
                NSDictionary *fData_1 = (NSDictionary *)[financialData objectAtIndex:KBarSartLocation+index-1-enterday ];            
                
                NSDecimalNumber *num1_MAMA ;
                num1_MAMA = [fData objectForKey:[NSString stringWithFormat:@"%@MAMA",idents] ];
                NSDecimalNumber *num1_FAMA ;
                num1_FAMA = [fData objectForKey:[NSString stringWithFormat:@"%@FAMA",idents] ];             
                
                NSDecimalNumber *num1_MAMA_1 ;
                num1_MAMA_1 = [fData_1 objectForKey:[NSString stringWithFormat:@"%@MAMA",idents] ];
                NSDecimalNumber *num1_FAMA_1 ;
                num1_FAMA_1 = [fData_1 objectForKey:[NSString stringWithFormat:@"%@FAMA",idents] ];                  
                
                
                if ([num1_FAMA floatValue]> [num1_MAMA floatValue] && [num1_FAMA_1 floatValue]< [num1_MAMA_1 floatValue] ) {
                    //賣出訊號
                    ssignal=YES;
                    scount=scount+1;
                            
                    
                }
                else if ([num1_FAMA floatValue] < [num1_MAMA floatValue] && [num1_FAMA_1 floatValue] > [num1_MAMA_1 floatValue] ){
                    //買入訊號
                    bsignal=YES;
                    bcount=bcount+1;           
                    
                }
                else{
                                        
                    
                    
                }
            
            
            
            }
            
            
            
        }
      
        //LF
        for (int j=0; j<[para_LF count]; j++) {
            if([[[para_LF objectAtIndex:j] valueForKey:@"isShow"] boolValue]){
                NSString *idents;
                idents =(NSString *)[[para_LF objectAtIndex:j] valueForKey:@"idendfiler"];              
               // NSLog(@"DD=%@",idents);
               
                NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:KBarSartLocation+index  ];
                NSDictionary *fData_1 = (NSDictionary *)[financialData objectAtIndex:KBarSartLocation+index-1  ];            
                
                NSDecimalNumber *lf_b ;
                lf_b = [fData_1 objectForKey:[NSString stringWithFormat:@"%@_b",idents] ];
                NSDecimalNumber *lf_s ;
                lf_s = [fData_1 objectForKey:[NSString stringWithFormat:@"%@_s",idents] ];             
                NSDecimalNumber *lf_bout ;
                lf_bout = [fData_1 objectForKey:[NSString stringWithFormat:@"%@_bout",idents] ];
                NSDecimalNumber *lf_sout ;
                lf_sout = [fData_1 objectForKey:[NSString stringWithFormat:@"%@_sout",idents] ];           
                
                NSDecimalNumber *lf_close ;
                lf_close= [fData objectForKey:@"close" ];                  
                
                //NSLog(@"lf_b=%i lf_s=%i lf_bout=%f lf_sout=%f close=%f " ,[lf_b intValue] ,[lf_s intValue],[lf_bout floatValue],[lf_sout floatValue] ,[lf_close floatValue]);
                
                if ( [lf_b intValue] ==1 && [lf_bout floatValue]>[lf_close floatValue] ) {
                    //賣出訊號
                    ssignal=YES;
                    scount=scount+1;
                    
                    
                }
                else if ([lf_s intValue] ==1 && [lf_sout floatValue]<[lf_close floatValue]  ){
                    //買入訊號
                    bsignal=YES;
                    bcount=bcount+1;           
                    
                }
                else{
                }
                
                
               }
            
        }        
        //循環三次 之後呈現訊號
        if (bsignal==YES) {
            static CPTMutableTextStyle *whiteText = nil;
            
            if (!whiteText) {
                whiteText = [[CPTMutableTextStyle alloc] init];
                whiteText.color = [CPTColor whiteColor ];
            }
            
            //如果同一時間出現兩個訊號以上就要改變數字
            CPTTextLayer *newLayer ; 
            if (bcount==1) {
                 newLayer= [[[CPTTextLayer alloc] initWithText:@"▲" style:whiteText] autorelease];
            }
            else if(bcount==2){
                 newLayer= [[[CPTTextLayer alloc] initWithText:@"▲2" style:whiteText] autorelease];
            }
            else if(bcount==3){
                 newLayer= [[[CPTTextLayer alloc] initWithText:@"▲3" style:whiteText] autorelease];                
            }
            else{
                 newLayer= [[[CPTTextLayer alloc] initWithText:@"▲0" style:whiteText] autorelease];   
            }    
                       
            
            newLayer.borderColor= [UIColor whiteColor].CGColor;
            newLayer.borderWidth=1.0f;
            newLayer.backgroundColor=[UIColor orangeColor].CGColor;
            
            
            return newLayer;             
            
        }
        else if(ssignal==YES){
            
            static CPTMutableTextStyle *whiteText = nil;
            
            if (!whiteText) {
                whiteText = [[CPTMutableTextStyle alloc] init];
                whiteText.color = [CPTColor whiteColor ];
            }
            
            CPTTextLayer *newLayer; 
          
            if (scount==1) {
                  newLayer = [[[CPTTextLayer alloc] initWithText:@"▼" style:whiteText] autorelease];
            }
            else if(scount==2){
                  newLayer = [[[CPTTextLayer alloc] initWithText:@"▼2" style:whiteText] autorelease];  
            }
            else if(scount==3){
                 newLayer = [[[CPTTextLayer alloc] initWithText:@"▼3" style:whiteText] autorelease];                
            }
            else{
                 newLayer = [[[CPTTextLayer alloc] initWithText:@"▼0" style:whiteText] autorelease];                
            }
                      
            
            newLayer.borderColor= [UIColor whiteColor].CGColor;
            newLayer.borderWidth=1.0f;
            newLayer.backgroundColor=[UIColor blueColor].CGColor;
            
            
            return newLayer;                  
            
        }
        else{
             return  (id)[NSNull null];            
            
        }
         
        
        
                
    }    
    else{
        return  (id)[NSNull null];
    }
    
    
    
} 
 
#pragma mark -
#pragma mark  走勢圖標記
 
 /*
-(CPLayer *)dataLabelForPlot:(CPPlot *)plot recordIndex:(NSUInteger)index {
  
	 
	
	if ( [(NSString *)plot.identifier hasPrefix:@"LF"] ){
		//NSLog(@"identfiler=%@  index=%i",plot.identifier,index);		
	 		
		
		if (index==0) {
			 
			CPTextLayer *label = [[CPTextLayer alloc] initWithText:@"w" ];
			label.textStyle.color = [CPColor lightGrayColor];
			return label;
			
			 			
		}
		else {
			return (id)[NSNull null]; // Don't show any label
		}
         
		 
	
	}
	else {
		return (id)[NSNull null]; // Don't show any label
	}			 
 	
}
 */
#pragma mark -
#pragma mark  切換日週月線 方法
-(void) segmentChanged:(id)sender{
	if (segmetnctl==sender) {
		
	 
		
		//================
	//CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
   // plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromUnsignedInteger([stockdata.financialData count]+[segmetnctl selectedSegmentIndex]) ];
		if (segmetnctl.selectedSegmentIndex==0 ) {
			 graph_dwm=@"d";
		}
		else if(segmetnctl.selectedSegmentIndex==1){
			 graph_dwm=@"w";		
		}
		else if(segmetnctl.selectedSegmentIndex==2){
			
			graph_dwm=@"m"	;		
		}		
		[segmetnctl setUserInteractionEnabled:NO];		
		
        
        [self.delgete SegmetnctlChange:graph_dwm indexr:0];
		 		
	}
}

#pragma mark -
#pragma mark  離開程式 或畫面事件 記憶體管理
- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}
- (void)dealloc {
	[graph release];
    [super dealloc];
}
 
#pragma mark -
#pragma mark  走勢圖觸控
//捏合方法
-(void)twofing_clsoe{

	
	if ( KBarLength-2<=10 ) {
		KBarLength =10 ;
		KBarSartLocation_limitLeft=stockdata.financialData.count -KBarLength;		
	}
	else{
		KBarLength =KBarLength-2 ;
		KBarSartLocation_limitLeft=stockdata.financialData.count -KBarLength;	
	}
	
	if ((KBarSartLocation+KBarLength)>=[stockdata.financialData count]+1){
		KBarSartLocation_move=5;
		KBarLength= graph_show_length;	
		KBarSartLocation=stockdata.financialData.count -KBarLength;	
		KBarSartLocation_limitLeft=stockdata.financialData.count -KBarLength;
		
	}
	
	 NSLog(@"twofing_clsoe");
	//NSLog(@"KBarSartLocation=%i",KBarSartLocation);
	//NSLog(@"KBarLength=%i",KBarLength);
	//NSLog(@"stockdata.financialData count=%i",[stockdata.financialData count]);
	//NSLog(@"KBarSartLocation_limitLeft=%i",KBarSartLocation_limitLeft);
	
	
	[self redrawChart:NO];	
	
}
-(void)twofin_out{
	
	
	if ((KBarSartLocation+KBarLength+2)<[stockdata.financialData count]-1) {
		KBarLength=KBarLength+2;
		KBarSartLocation_limitLeft=stockdata.financialData.count -KBarLength;
	}
	else {
		KBarLength=KBarLength+2;
		KBarSartLocation=KBarSartLocation-2;
		KBarSartLocation_limitLeft=stockdata.financialData.count -KBarLength;
	}

	 
	if ((KBarSartLocation+KBarLength)>=[stockdata.financialData count]+1){
		KBarSartLocation_move=5;
		KBarLength= graph_show_length;	
		KBarSartLocation=stockdata.financialData.count -KBarLength;	
		KBarSartLocation_limitLeft=stockdata.financialData.count -KBarLength;
		
	}
	
	 NSLog(@"twofin_out");
	//NSLog(@"KBarSartLocation=%i",KBarSartLocation);
	//NSLog(@"KBarLength=%i",KBarLength);
	//NSLog(@"stockdata.financialData count=%i",[stockdata.financialData count]);
	//NSLog(@"KBarSartLocation_limitLeft=%i",KBarSartLocation_limitLeft);
	
	[self redrawChart:NO];	
	
	
 


}



//水平方法
-(void)Horizontal_swipe_RL{
	if (self.delgete!=nil) {
        
        if ([stockdata.financialData count]> graph_show_length) {
            KBarSartLocation_limitLeft=stockdata.financialData.count -KBarLength;
            KBarSartLocation=KBarSartLocation+ KBarSartLocation_move;
            
            
            if ((KBarSartLocation+KBarLength)>=[stockdata.financialData count]+1){
                KBarSartLocation_move=5;
                KBarLength= graph_show_length;	
                KBarSartLocation=stockdata.financialData.count -KBarLength;	
                KBarSartLocation_limitLeft=stockdata.financialData.count -KBarLength;
                
            }
            //NSLog(@"Horizontal_swipe_RL");
            //NSLog(@"KBarSartLocation=%i",KBarSartLocation);
            //NSLog(@"KBarLength=%i",KBarLength);
            //NSLog(@"stockdata.financialData count=%i",[stockdata.financialData count]);
            //NSLog(@"KBarSartLocation_limitLeft=%i",KBarSartLocation_limitLeft);
            
            
            
            [self redrawChart:NO];	 
            
        }
        
        //左至右
        
        //UIAlertView *al;
        //al=[[UIAlertView alloc] initWithTitle:@"Touch" message:@"左至右" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil];
        //[al show];
        //[al release];        
        
        
    }
    
    
}
-(void)Horizontal_swipe_LR{
    if (self.delgete!=nil) {
        
        
        if ([stockdata.financialData count]> graph_show_length) {
            KBarSartLocation=KBarSartLocation- KBarSartLocation_move;
            
            if ( KBarSartLocation <=0 ) {
                KBarSartLocation=0;
            }
            
            if ((KBarSartLocation+KBarLength)>=[stockdata.financialData count]+1){
                KBarSartLocation_move=5;
                KBarLength= graph_show_length;	
                KBarSartLocation=stockdata.financialData.count -KBarLength;	
                KBarSartLocation_limitLeft=stockdata.financialData.count -KBarLength;
                
                
            }
            
            //NSLog(@"Horizontal_swipe_LR");
            //NSLog(@"KBarSartLocation=%i",KBarSartLocation);
            //NSLog(@"KBarLength=%i",KBarLength);
            //NSLog(@"stockdata.financialData count=%i",[stockdata.financialData count]);
            //NSLog(@"KBarSartLocation_limitLeft=%i",KBarSartLocation_limitLeft);
            
            [self redrawChart:NO];	 
            
            //右至左
            //UIAlertView *al;
            //al=[[UIAlertView alloc] initWithTitle:@"Touch" message:@"右至左" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil];
            //[al show];
            //[al release];		
        }
        
        
        
    }
   	
	
}
//垂直方法
//水平方法
-(void)Vertical_swipe_UD{
	NSLog(@"Vertical_swipe_UD_start");
    //標記:tabBarController 暫停使用 (暫停使用  Vertical_swipe)   
    [(AppDelegate * )AppleDeglate Set_tabBarController_DisEnable];
    
    //開始下載股價歷史資料時 將回歸扭隱藏
     self.navigationItem.hidesBackButton=YES;	    
    
    
    
    //標記:為何要加入nil 如果沒有在dealoc 中先指定nil 否則僅用release
    
    if (self.delgete!=nil) {
        
        [self resetLocationData];
        NSLog(@"Vertical_swipe_UD_1");	
        
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
            // 
            if (ActivityIndicator==nil ) {
                ActivityIndicator=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(320,450, 60, 60)];	
                ActivityIndicator.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                [self.view addSubview:ActivityIndicator];            
                
            }
            
            [ActivityIndicator  startAnimating];         
        }
        
        
        [segmetnctl setUserInteractionEnabled:NO];        
        
        
        NSLog(@"Vertical_swipe_UD_2");
        [self.delgete PreviousDrawGraph:0];
    }
        
    
	
	//左至右
	
	//UIAlertView *al;
	//al=[[UIAlertView alloc] initWithTitle:@"Touch" message:@"下至上" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil];
	//[al show];
	//[al release];
	NSLog(@"Vertical_swipe_UD_end");
}
-(void)Vertical_swipe_DU{
	NSLog(@"Vertical_swipe_DU_start1");	
    //標記:tabBarController 暫停使用 (暫停使用  Vertical_swipe)   
    [(AppDelegate * )AppleDeglate Set_tabBarController_DisEnable];
    
    //開始下載股價歷史資料時 將回歸扭隱藏
    self.navigationItem.hidesBackButton=YES;	
    if (self.delgete!=nil) {
        [self resetLocationData];
        
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
            // 
            if (ActivityIndicator==nil ) {
                ActivityIndicator=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(320,450, 60, 60)];	
                ActivityIndicator.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                [self.view addSubview:ActivityIndicator];            
                
            }
            
            [ActivityIndicator  startAnimating];         
        }
        
        
        [segmetnctl setUserInteractionEnabled:NO];        
        
        
        NSLog(@"Vertical_swipe_DU_start2");	        
        [self.delgete NextDrawGraph:0];
    }
    
	
	NSLog(@"Vertical_swipe_DU_END");	
	
	//右至左
	//UIAlertView *al;
	//al=[[UIAlertView alloc] initWithTitle:@"Touch" message:@"上至下" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil];
	//[al show];
	//[al release];
}


//觸控的委託事件定義與宣告
/*
 
  1.加入 自設 CPLayerHostEvent procol
  2.CPLayerHostingView * newView = [[CPLayerHostingView alloc]initWithFrame:[[UIScreen mainScreen] applicationFrame]];
    newView.delegete=self; 把物件委託給 CPLayerHostingView
  3.在CPLayerHostingView.m CPLayerHostingView.h 添加委託事件方法
 
 */ 


 
-(void)CPLayerHostEvent_touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
	 
	UITouch *touch = [touches anyObject];
	 
	int noTouchesInEvent  = ((NSSet*)[event allTouches]).count;
	int noTouchesBegan	  = touches.count;
	NSLog(@"began %i, total %i", noTouchesBegan, noTouchesInEvent);
	if((state == S0) && (noTouchesBegan== 1) && (noTouchesInEvent==1)){
		startLocation  = [touch locationInView:self.view];
		startTime	   = [(UITouch*)[touches anyObject] timestamp];
		state = S1;
	}
	else{
		state = S0;
		[self touchend];
	}	
	
	//捏合
	if ([touches count]==2) {
		NSArray *theTouches=[touches allObjects];
		UITouch *firstTouch=[theTouches objectAtIndex:0];
		UITouch *secondTouch=[theTouches objectAtIndex:1];
		originaDistance=distanceBetweenTwoPoints([firstTouch locationInView:self.view], [secondTouch locationInView:self.view]);
	}
	
	 	
}
-(void)CPLayerHostEvent_touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
	NSLog(@"CPLayerHostEvent_touchesMoved=%i",[touches count]);
    //捏合
	if ([touches count]==2) {
		//NSLog(@"aaaaa");
       //[self twofin_out];        
        NSArray *theTouches=[touches allObjects];
		UITouch *firstTouch=[theTouches objectAtIndex:0];
		UITouch *secondTouch=[theTouches objectAtIndex:1];
		CGFloat currentDistance=distanceBetweenTwoPoints([firstTouch locationInView:self.view], [secondTouch locationInView:self.view]);
        NSLog(@"currentDistance=%f originaDistance=%f ",currentDistance, originaDistance );
        if (originaDistance==0) {
		    originaDistance=currentDistance;
	   }
		else if(currentDistance-originaDistance>kminlength){
			 NSLog(@"outward");
			[self twofin_out];
		}
        else if(originaDistance-currentDistance>kminlength){
			 NSLog(@"close");
			[self twofing_clsoe];
		}

	
	}	
}
-(void)CPLayerHostEvent_touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
	NSLog(@"CPLayerHostEvent_touchesEnded_start");
	UITouch *touch = [touches anyObject];
	gestureStartPoint = [touch locationInView:self.view];
	
	int noTouchesInEvent  = ((NSSet*)[event allTouches]).count;
	int noTouchesEnded	  = touches.count;
	 
	if( (state==S1) && (noTouchesEnded == 1) && (noTouchesInEvent==1)){
		endLocation = [touch locationInView:self.view];
		endTime		= [(UITouch*)[touches anyObject] timestamp];
		[self touchend];
	}
	//捏合
	 
	originaDistance=0;
    NSLog(@"CPLayerHostEvent_touchesEnded_end");
}
-(void)CPLayerHostEvent_touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
}

-(void) touchend{
	NSLog(@"touchend_start");
	
	 
	if(state==S0){
	 
	}
	if(state == S1){
		 
		 
		
		 
		 //NSLog(message);
		//(fabs(startLocation.y - endLocation.y) <= Y_TOLERANCE)		
		
        
        //標籤:走勢圖的滑動 取消滑動事件		
		if (fabs(startLocation.y - endLocation.y) <= 80) {
			if(  startLocation.x - endLocation.x  >0){
				 [self performSelector:@selector(Horizontal_swipe_LR) withObject:nil afterDelay:0];
			}
			else{
				 [self performSelector:@selector(Horizontal_swipe_RL) withObject:nil afterDelay:0];
			}			
			
		}
		else {
			
			if(  startLocation.y - endLocation.y  >0){
				 [self performSelector:@selector(Vertical_swipe_DU) withObject:nil afterDelay:0];
			}
			else{
				 [self performSelector:@selector(Vertical_swipe_UD) withObject:nil afterDelay:0];
			}			
			
			 
		}

		
	
		
		
		
		state = S0;
	}
	NSLog(@"touchend_end");
}
 

#pragma mark -
#pragma mark  移動查價
-(void)scatterPlot:(CPTScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)index{
 //	NSLog(@"scatterPlot");
}
-(void)barPlot:(CPTBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index{
	//NSLog(@"barWasSelectedAtRecordIndex %d", index);
	/*
	if ( symbolTextAnnotation ) {
        [graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
        symbolTextAnnotation = nil;
    }
    
    // Setup a style for the annotation
    CPTextStyle *hitAnnotationTextStyle = [CPTextStyle textStyle];
    hitAnnotationTextStyle.color = [CPColor redColor];
    hitAnnotationTextStyle.fontSize = 16.0f;
    hitAnnotationTextStyle.fontName = @"Helvetica-Bold";
    
    // Determine point of symbol in plot coordinates
	
    NSNumber *x = [NSNumber numberWithInt:0];
	NSNumber *y = [self numberForPlot:plot field:0 recordIndex:index];
	NSArray *anchorPoint = [NSArray arrayWithObjects:x, [NSNumber numberWithInt:index], nil];
    
    // Add annotation
    // First make a string for the y value
    NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
    [formatter setMaximumFractionDigits:2];
    NSString *yString = [formatter stringFromNumber:y];
    
	
    // Now add the annotation to the plot area
    CPTextLayer *textLayer = [[[CPTextLayer alloc] initWithText:yString style:hitAnnotationTextStyle] autorelease];
    symbolTextAnnotation = [[[CPPlotSpaceAnnotation alloc] initWithPlotSpace:plot.plotSpace anchorPlotPoint:anchorPoint] autorelease];
	symbolTextAnnotation.contentLayer = textLayer;
    symbolTextAnnotation.displacement = CGPointMake(0.0f, 0.0f);
    [graph.plotAreaFrame.plotArea addAnnotation:symbolTextAnnotation];    
	 */
}

#pragma mark -
#pragma mark plotSpace 觸控方法
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDownEvent:(id)event atPoint:(CGPoint)point{
	/*
	int ff=[[event allTouches] count];
	NSLog(@"shouldHandlePointingDeviceDownEvent: %i",ff);
	*/
	 return YES;
	 
}
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDraggedEvent:(id)event atPoint:(CGPoint)point{
	/*
	int ff=[[event allTouches] count];
	NSLog(@"shouldHandlePointingDeviceDraggedEvent: %i",ff);
	int aa=((NSSet *)[event allTouches]).count;
	NSLog(@"shouldHandlePointingDeviceDraggedEvent nssett: %i",aa);
	
	int x=point.x;
	int y=point.y;
	NSLog(@"x=%i y=%i",x,y);
	 */
	return YES;	
	 
}
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceCancelledEvent:(id)event{
/*
	int ff=[[event allTouches] count];
	NSLog(@"shouldHandlePointingDeviceCancelledEvent: %i",ff);
	*/
    return YES;
 	
}
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceUpEvent:(id)event atPoint:(CGPoint)point{
	/*
	int ff=[[event allTouches] count];
	NSLog(@"shouldHandlePointingDeviceUpEvent %i",ff);
	*/
	return YES;
 
}

 
//標籤:走勢圖的滑動 限制事件

-(CGPoint)plotSpace:(CPTPlotSpace *)space willDisplaceBy:(CGPoint)displacement {
    return CGPointMake(displacement.x, 0);
}




 
#pragma mark -
#pragma mark  函數 高低價 高低量
-(NSDecimalNumber *)turnNSDecimalNumber:(NSDecimalNumber *)inp{
	NSString *h;
	//h=[[NSString alloc] init];
	h=[inp stringValue];
	inp=[NSDecimalNumber decimalNumberWithString:h];
	//[h autorelease];
	return inp;
}



-(NSDecimalNumber *)HighPrice:(DataObject *)aDataObject startX:(int)astartX count:(int)acount{
	NSDecimalNumber *outc;	
	outc=[NSDecimalNumber notANumber];	
	 
	for (int i=astartX; i< (astartX+acount); i++) {
	
		if (i<[stockdata.financialData count]) {
			NSArray *financialData = stockdata.financialData;
			NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:i];
			
			NSDecimalNumber *high = [fData objectForKey:@"high"];	
			
			 	
			
			if ( [outc isEqual:[NSDecimalNumber notANumber]] ) {
				outc= high;
			}		
			if ( [high compare:outc] == NSOrderedDescending ) {
				outc = high;
			}		
		}
		
		
	}
	
	
	return [self turnNSDecimalNumber:outc];

	
}

-(NSDecimalNumber *)LowPrice:(DataObject *)aDataObject startX:(int)astartX count:(int)acount{
	NSDecimalNumber *outc;	
	outc=[NSDecimalNumber notANumber];	
	
	for (int i=astartX; i< (astartX+acount); i++) {
		if (i<[stockdata.financialData count]) {
			NSArray *financialData = stockdata.financialData;
			NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:i];
			
			NSDecimalNumber *low = [fData objectForKey:@"low"];	
			if ( [outc isEqual:[NSDecimalNumber notANumber]] ) {
				outc= low;
			}		
			if ( [low compare:outc] == NSOrderedAscending ) {
				outc = low;
			}				
		
		}		
		
	
	}
	
	
	return [self turnNSDecimalNumber:outc];

	
}

-(NSDecimalNumber *)HighVolume:(DataObject *)aDataObject startX:(int)astartX count:(int)acount{
	NSDecimalNumber *outc;	
	outc=[NSDecimalNumber notANumber];	
	
	for (int i=astartX; i< (astartX+acount); i++) {
		if (i<[stockdata.financialData count]) {
			NSArray *financialData = stockdata.financialData;
			NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:i];
			
			NSDecimalNumber *high = [fData objectForKey:@"volume"];	
			if ( [outc isEqual:[NSDecimalNumber notANumber]] ) {
				outc= high;
			}		
			if ( [high compare:outc] == NSOrderedDescending ) {
				outc = high;
			}				
		}		
		
		
	}
	
	
	return [self turnNSDecimalNumber:outc];

	
}

-(NSDecimalNumber *)LowVolume:(DataObject *)aDataObject startX:(int)astartX count:(int)acount{
	NSDecimalNumber *outc;	
	outc=[NSDecimalNumber notANumber];	
	
	for (int i=astartX; i< (astartX+acount); i++) {
		if (i<[stockdata.financialData count]){
		
			
			
			
			NSArray *financialData = stockdata.financialData;
			NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:i];
			
			NSDecimalNumber *low = [fData objectForKey:@"volume"];	
			if ( [outc isEqual:[NSDecimalNumber notANumber]] ) {
				outc= low;
			}		
			if ( [low compare:outc] == NSOrderedAscending ) {
				outc = low;
			}					
		
		}
			
			
		
	}
	
	
	return [self turnNSDecimalNumber:outc];

	
}

#pragma mark -
#pragma mark  函數 Lable日期轉換

-(NSString *)LableDateString:(int)Index{
	 	
	if (Index<[stockdata.financialData count]) {
		NSArray *financialData = stockdata.financialData;
		NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:Index];
		NSDate *theDate= [fData objectForKey:@"date"];	
		
		NSDateFormatter* df = [[NSDateFormatter alloc]init];
		[df setDateFormat:@"MM/dd"];
		NSString *result = [df stringFromDate:theDate];
		[df release];	
		return result;		
	}
	 else {
		 return @"na";
	 }

	
	
}

-(NSString *)LableDateStringYear:(int)Index{
	
	if (Index<[stockdata.financialData count]) {
		NSArray *financialData = stockdata.financialData;
		NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:Index];
		NSDate *theDate= [fData objectForKey:@"date"];	
		
		NSDateFormatter* df = [[NSDateFormatter alloc]init];
		[df setDateFormat:@"yyyy"];
		NSString *result = [df stringFromDate:theDate];
		[df release];	
		return result;		
	}
	else {
		return @"na";
	}
	
	
	
}


@end



/*
 如果core plot 要升級 請修改下面函數方法
  /source/
  CPTradingRangePlot.h CPTradingRangePlot.m	 
  目的：可以更改Ｋ線顏色
  
  /iphone only/
  CPLayerHostingView.h CPLayerHostingView.m 
  目的：觸控方法委託事件的增加
 
 如何取的最新的core plot framework
 到應用程式裡的工具 開啓終端機 輸入 “hg clone http://core-plot.googlecode.com/hg/ core-plot"
 所有的資料就會下載 到user 目錄下 中的 core plot資料夾
 
 */
